﻿using System;
using System.Collections.Generic;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YArchitech.Revit;

namespace YArchitech.Plumbing
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class CreateViewSection : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			UIApplication application = commandData.Application;
			UIDocument activeUIDocument = application.ActiveUIDocument;
			Document document = activeUIDocument.Document;
			if (!YJKRevitTools.ViewCheck(activeUIDocument, new List<ViewType>
			{
				(ViewType)1,
				(ViewType)2,
				(ViewType)3,
				(ViewType)117
			}))
			{
				return Autodesk.Revit.UI.Result.Cancelled;
			}
			application.PostCommand(RevitCommandId.LookupPostableCommandId(Autodesk.Revit.UI.PostableCommand.Section));
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		private bool GenerateBoundingBoxXYZ(XYZ first, XYZ second, XYZ touying, XYZ third)
		{
			Transaction transaction = new Transaction(this.m_project.Document, "GenerateBoundingBox");
			transaction.Start();
			this.m_box = new BoundingBoxXYZ();
			this.m_box.Enabled = true;
			XYZ max = new XYZ(this.length / 2.0, 0.0, 0.0);
			XYZ min = new XYZ(-this.length / 2.0, -this.length / 2.0, -this.heigth);
			this.m_box.Max = max;
			this.m_box.Min = min;
			Transform transform = this.GenerateTransform(first, second, touying, third);
			if (transform == null)
			{
				return false;
			}
			this.m_box.Transform = transform;
			transaction.Commit();
			return true;
		}

		private Transform GenerateTransform(XYZ first, XYZ second, XYZ touying, XYZ third)
		{
			Transform identity = Transform.Identity;
			identity.Origin = third;
			XYZ xyz = XYZMath.FindDirection(first, second, XYZMath.GetDirectionVector(touying, third));
			XYZ xyz2 = XYZMath.FindRightDirection(xyz);
			XYZ xyz3 = XYZMath.FindUpDirection();
			identity.set_Basis(0, xyz2);
			identity.set_Basis(1, xyz3);
			identity.set_Basis(2, xyz);
			return identity;
		}

		private UIDocument m_project;

		private BoundingBoxXYZ m_box;

		public double length = 20.0;

		public double heigth = 10.0;
	}
}
